package zzjson.rabbitmq.returnlistener;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ReturnListener;
import zzjson.rabbitmq.BaseRabbitMq;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * <p>****************************************************************************</p>
 * <p><b>Copyright © 2010-2019 shuncom team All Rights Reserved<b></p>
 * <ul style="margin:15px;">
 * <li>Description : zzjson.rabbitmq.returnlistener</li>
 * <li>Version     : 1.0.0</li>
 * <li>Creation    : 2019年04月29日</li>
 * <li>@author     : zzy0_0</li>
 * </ul>
 * <p>****************************************************************************</p>
 */
public class ReturnListenerProducer {
	public static void main(String[] args) throws Exception {
		Connection conn = BaseRabbitMq.getConn();
		Channel channel = conn.createChannel();

		channel.addReturnListener(new ReturnListener() {
			@Override
			public void handleReturn(int replyCode, String replyText, String exchange, String routingKey, AMQP.BasicProperties properties, byte[] body) throws IOException {
				System.out.println("=========监听器收到了无法路由，被返回的消息============");
				System.out.println("replyText:" + replyText);
				System.out.println("exchange:" + exchange);
				System.out.println("routingKey:" + routingKey);
				System.out.println("message:" + new String(body));
			}
		});
		AMQP.BasicProperties properties = new AMQP.BasicProperties.Builder().deliveryMode(2).
				contentEncoding("UTF-8").build();

		// 在声明交换机的时候指定备份交换机
		//Map<String,Object> arguments = new HashMap<String,Object>();
		//arguments.put("alternate-exchange","ALTERNATE_EXCHANGE");
		//channel.exchangeDeclare("TEST_EXCHANGE","topic", false, false, false, arguments);

		// 发送到了默认的交换机上，由于没有任何队列使用这个关键字跟交换机绑定，所以会被退回
		// 第三个参数是设置的mandatory，如果mandatory是false，消息也会被直接丢弃
		channel.basicPublish("", "nondirect", true, properties, "无法路由的消息".getBytes());

		TimeUnit.SECONDS.sleep(10);

		BaseRabbitMq.close(channel, conn
		);

	}
}